package org.pentaho.di.trans.util;

import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liy
 * @date 2022-10-12 16:03
 */
public class DataFileCacher {

    FileInputStream is;
    ObjectInputStream ois;
    boolean first = true;
    private String cacheFileName;

    public DataFileCacher(String cacheFileName) {
        this.cacheFileName = cacheFileName;
    }

    public void serializObjectToFile(List<Object[]> list) {
        boolean isExist = false;
        File file = new File(cacheFileName);
        if (file.exists()) {
            isExist = true;
        }
        FileOutputStream os = null;
        ObjectOutputStream oos = null;
        try {
            os = new FileOutputStream(file, true);
            oos = new ObjectOutputStream(os);
            if (isExist) {
                long pos = os.getChannel().position() - 4;
                os.getChannel().truncate(pos);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                oos.writeObject(list);
                oos.close();
                os.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }

    }

    public List<Object[]> deserializeFileToObject() {

        try {
            if (first) {
                is = new FileInputStream(new File(cacheFileName));
                ois = new ObjectInputStream(is);
                first = false;
            }

            if (is.available() > 0) {
                return (List<Object[]>) ois.readObject();
            }
        } catch (Exception e) {
            close(true);
            e.printStackTrace();
        }
        return null;
    }

    public void close(boolean dropFile){
        try {
            if(ois!=null){
                ois.close();
            }
           if(is!=null){
               is.close();
           }

        } catch (IOException ee) {
            ee.printStackTrace();
        }
        if(dropFile){
            dropCacheFile();
        }

    }

    public void dropCacheFile() {
        File file = new File(cacheFileName);
        file.delete();
    }
}
